<?php

namespace api\modules\v1\models\search;

use yii\base\Model;
use yii\data\ActiveDataProvider;
use api\modules\v1\models\Article;

/**
 * ArticleSearch represents the model behind the search form of `api\modules\v1\models\Article`.
 */
class ArticleSearch extends Article
{
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id', 'type', 'created_at', 'updated_at'], 'integer'],
            [['title', 'connect'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params, $page_size)
    {
        $query = Article::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => $page_size ? $page_size : 20,
            ],
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'type' => $this->type,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ]);

        $query->andFilterWhere(['like', 'title', $this->title])
            ->andFilterWhere(['like', 'connect', $this->connect]);

        // 数据权限过滤
        $query->andWhere(['uid'=>$this->loginUser->id]);

        // 默认排序，TODO 可以根据 ActiveDataProvider 排序方式进行参数传递
        $query->orderBy(['created_at'=>SORT_DESC]);

        return $dataProvider;
    }
}
